#!/bin/bash

function reset_cluster {
    echo "Resetting cluster"
    charts=$(helm ls --all --short)
    if [[ ! -z "$charts" ]]; then
        helm del $charts || :
    fi
    system_charts=$(helm ls --all --short --namespace kube-system)
    if [[ ! -z "$system_charts" ]]; then
        helm del $system_charts --namespace kube-system || :
    fi
    for node in $(kubectl get nodes | tail -n+2 | cut -d' ' -f1); do
        kubectl uncordon $node
        kubectl taint node $node aws-node-termination-handler/scheduled-maintenance- || true
        kubectl taint node $node aws-node-termination-handler/spot-itn- || true
    done
    remove_labels || :
    sleep 2
}

function remove_labels {
    echo "Removing labels from NTH cluster nodes"
    
    labels_to_remove=()
    while IFS='' read -r line; do 
      labels_to_remove+=("$line"); 
    done < <(kubectl get nodes -o json | jq '.items[].metadata.labels' | grep 'aws-node-termination-handler' | tr -d '[:blank:]' | tr -d '\"' | cut -d':' -f1)

    if [[ "${#labels_to_remove[@]}" -ne 0 ]]; then
      for l in "${labels_to_remove[@]}"; do
        for n in $(kubectl get nodes -o json | jq -r '.items[].metadata.name'); do
          echo "Deleting label $l on node $n"
          kubectl label node $n "$l"-
        done
      done
    fi
}

reset_cluster
echo "✅  reset done"
